import React, { Component } from "react";
import PropTypes from "prop-types";

class Comment extends Component {
  constructor() {
    super();
    this.state = {
      timeString: ""
    };
  }

  componentWillMount() {
    this._updataTimeString();
    this._timer = setInterval(this._updataTimeString.bind(this), 5000);
  }

  componentWillUnmount() {
    clearInterval(this._timer);
  }

  _updataTimeString() {
    const { comment } = this.props;
    const duration = (+Date.now() - comment.createdTime) / 1000; // 毫秒转换为秒

    this.setState({
      timeString:
        duration > 60
          ? `${Math.round(duration / 60)} 分钟前`
          : `${Math.round(Math.max(duration, 1))} 秒前`
    });
  }

  _getProcessedContent(content) {
    return content
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;")
      .replace(/`([\S\s]+?)`/g, "<code>$1</code>");
  }
  handleDeleteComment = () => {
    const { onDeleteComment, index } = this.props;
    if (onDeleteComment) {
      onDeleteComment(index);
    }
  };

  render() {
    return (
      <div className="comment">
        <div className="comment-user">
          <span>{this.props.comment.username} </span>：
        </div>
        <p
          dangerouslySetInnerHTML={{
            __html: this._getProcessedContent(this.props.comment.content)
          }}
        />
        <span className="comment-createdtime">{this.state.timeString}</span>
        <span className="comment-delete" onClick={this.handleDeleteComment}>
          删除
        </span>
      </div>
    );
  }
}

Comment.propTypes = {
  comment: PropTypes.object.isRequired,
  index: PropTypes.number,
  onDeleteComment: PropTypes.func
};

export default Comment;
